<script setup>
import { inject, onMounted, ref, toRaw } from 'vue'
//图标
import { IconArrowLeft, IconLock,IconUser,IconEyeClosed,IconEye,IconEditUser,IconHandphone,IconGallery } from '../icon/index.js'
//消息提示工具
import { DlMessageBox } from '../util/messagebox.js'

//引入 api
import { userInfoModifyFun, userPwdModifyFun, userLogOutFun } from '../api/user.js'

//主菜单核心
const menuCore = inject('menuCore');
//返回
function doGoBack() {
    menuCore.back();
}

//登录用户缓存
const loginUser = inject('loginUser');
//是否登录
const isLogin = ref(false);
function doCheckLogin() {
    if(!loginUser.value || !loginUser.value.token) {
        DlMessageBox.error('您还未登录,\n请先登录!');
        menuCore.push('/login');
        return;
    }
    isLogin.value = true;
    let user = loginUser.value;
    currentUser.value = {loginName: user.loginName, nickname: user.nickname, phone: user.phone, headImage: '', filename: ''};
}

//用于编辑的user对象
const currentUser = ref({});
//头像
const fileInputRef = ref(null);
const headFile = ref();
const previewHeadFileUrl = ref(null);
function doChangeFile() {
    let files = fileInputRef.value.files;
    if(files.length > 0) {
        let file = files[0];
        //console.log('file:', file);
        //限制类型:图片
        if(file.type.startsWith('image')){
            currentUser.value.filename = file.name;
            previewHeadFileUrl.value = URL.createObjectURL(file);
            headFile.value = file;
            return;
        }
    }
    currentUser.value.filename = '';
    headFile.value = null;
    previewHeadFileUrl.value = null;
    DlMessageBox.error('请选择图片文件作为头像');
}

function doModifyUserInfo() {
    //修改用户信息
    //封装修改操作的参数(api中已进行了文件处理)
    // let formData = new FormData();
    // formData.append('nickname', currentUser.value.nickname);
    // formData.append('phone', currentUser.value.phone);
    //获取头像文件
    let file = headFile.value;
    // console.log('params.file=', file);
    let headImageFile = null;
    if(file) {
        //formData.append('headImage', headFile.value);
        headImageFile = headFile.value;
    }
    //测试,输出请求需要参数
    //formData.forEach((val, name) => console.log(name, val));

    if (window && window.enableDl) {
        //模拟
        DlMessageBox.success('修改成功');
        //成功后执行以下操作
        let user = toRaw(loginUser.value);

        //如果有修改头像, 需要获取最新头像地址
        //currentUser.value.headImage = '新头像地址';
        //如果有修改头像, 则把前面获取的最新头像地址 也同步修改到本地
        //user.headImage = currentUser.value.headImage;

        //更新本地存储的用户信息
        user.nickname = currentUser.value.nickname;
        user.phone = currentUser.value.phone;
        localStorage.setItem("loginUser", JSON.stringify(user));
    } else {
        //请求api
        userInfoModifyFun(currentUser.value.nickname, currentUser.value.phone, headImageFile).then((result)=>{
            console.log('userInfoModifyFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //成功后执行以下操作
                let user = toRaw(loginUser.value);
                //如果有修改头像, 需要获取最新头像地址
                if (result.data) {
                    currentUser.value.headImage = result.data;
                    //如果有修改头像, 则把前面获取的最新头像地址 也同步修改到本地
                    user.headImage = currentUser.value.headImage;
                }
                //更新本地存储的用户信息
                user.nickname = currentUser.value.nickname;
                user.phone = currentUser.value.phone;
                localStorage.setItem("loginUser", JSON.stringify(user));
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }

}

const pwdData = ref({oldPwd: '', newPwd: '', rePwd: '', lock1: true, lock2: true, lock3: true});
function doModifyPwd() {
    //修改密码

    let params = {
        oldPwd: pwdData.value.oldPwd,
        newPwd: pwdData.value.newPwd,
        rePwd: pwdData.value.rePwd,
    };
    console.log('params:', params);
    if(!params.oldPwd) {
        DlMessageBox.warning('请输入原密码');
        return;
    }
    if(!params.newPwd) {
        DlMessageBox.warning('请输入新密码');
        return;
    }
    if(params.newPwd != params.rePwd) {
        DlMessageBox.warning('确认密码与新密码\n不一致');
        return;
    }
    
    if (window && window.enableDl) {
        //模拟
        DlMessageBox.success('修改成功');
        //修改成功后执行以下操作
        //自动执行退出,并清空状态,再让用户重新登录
        //清空用户状态
        localStorage.removeItem('loginUser');
        localStorage.removeItem('token');
        localStorage.removeItem('cart');
        //回到登录
        menuCore.push('/login');
    } else {
        //请求api
        userPwdModifyFun(params.oldPwd, params.newPwd, params.rePwd).then((result)=>{
            //result.code = 200;//测试代码
            //result.msg = '密码修改成功';//测试代码
            console.log('userPwdModifyFun result:', result);
            if (result.code == 200) {
                DlMessageBox.success(result.msg);
                //修改成功后执行以下操作
                //自动执行退出,并清空状态,再让用户重新登录
                //请求api
                userLogOutFun().then((result)=>{
                    console.log('userLogOutFun result:', result);
                    if (result.code == 200) {
                        DlMessageBox.success(result.msg);
                    } else {
                        DlMessageBox.error(result.msg);
                    }
    
                    //清空用户状态
                    localStorage.removeItem('loginUser');
                    localStorage.removeItem('token');
                    localStorage.removeItem('cart');
                    //回到登录
                    menuCore.push('/login');
                });
            } else {
                DlMessageBox.error(result.msg);
            }
        });
    }

}


onMounted(()=>{
    doCheckLogin();
});

</script>
<template>
    <div class="view-dl">
        <!-- 顶部 -->
        <div class="top-head-dl">
            <IconArrowLeft class="back-icon" @click="doGoBack" />
            <div class="title-dl">个人资料</div>
        </div>

        <div class="view-body-dl">
            <div class="base-box-dl">
                <div class="box-title-dl">基本信息</div>
                <div class="input-box-dl">
                    <IconUser class="left-icon-dl" />
                    <input class="input-dl" type="text" placeholder="请输入用户名" v-model="currentUser.loginName" readonly>
                </div>
                <div class="input-box-dl">
                    <IconEditUser class="left-icon-dl" />
                    <input class="input-dl" type="text" placeholder="请输入昵称" v-model="currentUser.nickname">
                </div>
                <div class="input-box-dl">
                    <IconHandphone class="left-icon-dl" />
                    <input class="input-dl" type="text" placeholder="请输入手机号" v-model="currentUser.phone">
                </div>
                <div class="input-box-dl">
                    <IconGallery class="left-icon-dl" />
                    <input class="input-dl" type="text" placeholder="可修改头像" v-model="currentUser.filename" readonly @click="fileInputRef.click()">
                    <input type="file" class="file-input-dl" ref="fileInputRef" @change="doChangeFile" >
                </div>
                <div class="input-box-dl">
                    <div style="font-size:0.5rem;" >预览:</div>
                    <div class="user-head-img-dl" >
                        <img :src="previewHeadFileUrl" alt="暂无图片">
                    </div>
                </div>

                <div class="btn-list-dl" >
                    <div class="btn-dl" @click="doModifyUserInfo">确定</div>
                </div>

            </div>
            <div class="pwd-box-dl">
                <div class="box-title-dl">密码修改</div>

                <div class="input-box-dl">
                    <IconLock class="left-icon-dl" />
                    <input class="input-dl" :type="(pwdData.lock1 ? 'password':'text')" placeholder="请输入原密码" v-model="pwdData.oldPwd">
                    <IconEyeClosed class="right-icon-dl" style="color: #777;" @click="pwdData.lock1=!pwdData.lock1" v-if="pwdData.lock1" />
                    <IconEye class="right-icon-dl" @click="pwdData.lock1=!pwdData.lock1" v-else />
                </div>
                <div class="input-box-dl">
                    <IconLock class="left-icon-dl" />
                    <input class="input-dl" :type="(pwdData.lock2? 'password':'text')" placeholder="请输入新密码" v-model="pwdData.newPwd">
                    <IconEyeClosed class="right-icon-dl" style="color: #777;" @click="pwdData.lock2=!pwdData.lock2" v-if="pwdData.lock2" />
                    <IconEye class="right-icon-dl" @click="pwdData.lock2=!pwdData.lock2" v-else />
                </div>
                <div class="input-box-dl">
                    <IconLock class="left-icon-dl" />
                    <input class="input-dl" :type="(pwdData.lock3? 'password':'text')" placeholder="请输入确认密码" v-model="pwdData.rePwd">
                    <IconEyeClosed class="right-icon-dl" style="color: #777;" @click="pwdData.lock3=!pwdData.lock3" v-if="pwdData.lock3" />
                    <IconEye class="right-icon-dl" @click="pwdData.lock3=!pwdData.lock3" v-else />
                </div>

                <div class="btn-list-dl" >
                    <div class="btn-dl" @click="doModifyPwd">确定</div>
                </div>

            </div>
        </div>

    </div>
</template>
<style scoped>
.view-dl {
    font-size: 0.4rem;
    height: 100%;
    overflow: hidden auto;
}
.top-head-dl {
    background-color: #fff;
    color: #333;
    padding: 0.2rem;
    position: sticky;
    top: 0;
    z-index: 2;
}
.top-head-dl .back-icon {
    width: 0.8rem;
    height: 0.8rem;
    cursor: pointer;
    position: absolute;
    top: 50%;
    left: 0.2rem;
    transform: translate(0, -50%);
}
.top-head-dl .title-dl {
    font-size: 0.7rem;
    text-align: center;
}

.view-body-dl {
    padding: 0.2rem;
}


.input-box-dl {
    position: relative;
    margin: 0.6rem 0;
    color: #333;
}
.input-box-dl .left-icon-dl {
    width: 0.8rem;
    height: 0.8rem;
    position: absolute;
    top: 50%;
    left: 0.2rem;
    transform: translate(0, -50%);
}
.input-box-dl .right-icon-dl {
    width: 0.8rem;
    height: 0.8rem;
    position: absolute;
    top: 50%;
    right: 0.2rem;
    transform: translate(0, -50%);
    cursor: pointer;
    user-select: none;
}
.input-box-dl .input-dl {
    font-size: 0.6rem;
    padding: 0.2rem 1.1rem;
    width: 100%;
    box-sizing: border-box;
    border-radius: 0.6rem;
}
.input-box-dl .file-input-dl {
    display: none;
}

.btn-list-dl {
    text-align: center;
    margin-bottom: 0.4rem;
}
.btn-list-dl .btn-dl {
    font-size: 0.6rem;
    color: #fff;
    background-color: #900000;
    padding: 0.1rem 0.8rem;
    border-radius: 0.6rem;
    display: inline-block;
    cursor: pointer;
    user-select: none;
}
.btn-list-dl .btn-dl:hover {
    background-color: #d00000;
}
.btn-list-dl .btn-dl:active {
    transform: scale(0.9) translateY(5px);
}

.user-head-img-dl {
    margin-top: 0.1rem;
    width: 4rem;
    height: 4rem;
    border-radius: 50%;
    text-align: center;
    line-height: 4rem;
    overflow: hidden;
    border: 1px solid #333;
}
.user-head-img-dl img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
    font-size: 0.4rem;
    display: block;
}

.base-box-dl {
    padding: 0.2rem;
    background-color: #fff;
    margin-bottom: 0.2rem;
    border-radius: 0.1rem;
}

.pwd-box-dl {
    padding: 0.2rem;
    background-color: #fff;
    border-radius: 0.1rem;
}

.box-title-dl {
    font-size: 0.6rem;
    font-weight: bold;
    color: #333;
}



</style>